package com.infore.dataAudit.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.infore.dataAudit.enums.ResultStatus;
import com.infore.dataAudit.service.DeployService;
import com.infore.dataAudit.service.RunningTimeService;
import com.infore.dataAudit.util.ResultEntity;





/**
 * 
 * @author cys
 * 流程控制接口层 公开
 */
@RestController
@RequestMapping("/activity")
public class ActivitiController {
    @Resource
    private DeployService deployService;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private RunningTimeService runningTimeService;
    @Resource
    private TaskService taskService;
    @Resource
    private HistoryService historyService;
    @Resource
    private ObjectMapper objectMapper;
    
    /**
     * 开始一个流程 启动流程实例
     * 20001
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param param 流程实例的属性数据 及流程部署定义的key
     * @return 流程实例id
     * @date 2019年2月28日下午3:42:15
     */
    @ResponseBody
    @RequestMapping(value = "/startProcessInstance", method = {RequestMethod.POST})
    public ResultEntity startProcessInstanceBykey(@RequestParam(required = true)Map<String, Object> param) {
       String key = param.get("key").toString();
       return runningTimeService.startProcess(key, param);
    }
    
    /**
     * 结束关掉停止一个流程实例 
     * 
     * @author 蔡永顺
     * @return ResultEntity
     * @param key 流程实例id
     * @param reason 备注
     * @return
     * @date 2019年2月28日下午4:04:40
     */
    @ResponseBody
    @RequestMapping(value = "/stopProcessByKey", method = {RequestMethod.GET})
    public ResultEntity stopProcessByKey(@RequestParam(required = true)String key,
            @RequestParam(required = false)String reason) {
       return runningTimeService.stopProcessByKey(key, reason);
    }
    
    /**
     * 获取流程实例的流程图
     * 直接在response 无需再返回实体数据
     * @author 蔡永顺
     * @return ResultEntity
     * @param instanceId 流程实例id
     * @param response
     * @return
     * @throws IOException
     * @date 2019年2月28日下午4:35:58
     */
    @RequestMapping(value = "/processPicByInstanceId", method = {RequestMethod.GET, RequestMethod.POST})
    public void getProcessPicByInstanceId(@RequestParam(required = true)String instanceId, HttpServletResponse response)
            throws IOException {
        response.setContentType("image/jpeg");
        InputStream is = null;
        try {
            is = runningTimeService.generateDiagram(instanceId);
            byte[] bytes = new byte[1024];
            ServletOutputStream os = response.getOutputStream();
            int length = -1;
            while ((length = is.read(bytes)) != -1) {
                os.write(bytes, 0, length);
            }
            response.flushBuffer();
        } finally {
            if (is != null) {
                is.close();
            }
        }
       // return new ResultEntity(ResultStatus.SUCCESS,"流程图获取成功");
    }
    
    /**
     * 流程用户任务审批信息
     * 服务任务 serviceTask未查询
     * @author 蔡永顺
     * @return ResultEntity
     * @param instanceId 流程实例id
     * @return
     * @date 2019年3月21日上午11:03:10
     */
    @ResponseBody
    @RequestMapping(value = "/processInstanceInfo", method = RequestMethod.GET)
    public ResultEntity queryProcessInstanceInfo(@RequestParam String instanceId) {
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId)
                .singleResult();
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(instanceId)
                .orderByDueDateNullsLast().asc().list();
//        List<HistoricActivityInstance> hisList = historyService.createHistoricActivityInstanceQuery()
//                .processInstanceId(instanceId).orderByHistoricActivityInstanceStartTime().asc()
//                .activityType("serviceTask").activityType("userTask").list();
        List<Map<String, Object>> resList = new ArrayList<>();
        if (list != null) {
            Map<String, Object> map2 = null;
            for (HistoricTaskInstance hai : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", hai.getId());
                map.put("processID", hai.getProcessInstanceId());
                map.put("name", hai.getName());
                map.put("startTime", hai.getStartTime());
                map.put("endTime", hai.getEndTime());
                map.put("user", hai.getAssignee());
                map.put("deleteReason", hai.getDeleteReason());
                String appUserId = hai.getAssignee();
                map.put("appUser", appUserId);
                List<Comment> liComments = taskService.getTaskComments(hai.getId());
                String comment = "";
                if ("deleted".equals(hai.getDeleteReason())) {
                    comment = "超时自动完成";
                }
                if (liComments.size() > 0) {
                    comment = liComments.get(0).getFullMessage();
                }
                /*
                 * if (attFiles !=null) { //map.put("attFiles", attFiles); }
                 */
                map.put("comment", comment);
                map2 = new HashMap<>(map);
                resList.add(map);
            }
            if (instance == null) {
                map2.put("name", "结束节点");
                map2.put("appUser", "系统");
                map2.put("deleteReason", "结束流程");
                resList.add(map2);
            }

        }
        return new ResultEntity(ResultStatus.SUCCESS, "查询成功").setDataList(resList);
    }

    @ResponseBody
    @RequestMapping(value = "/completeTask", method = RequestMethod.GET)
    public ResultEntity completeTask(@RequestParam String instanceId) {
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(instanceId).list();
        for (Task task : tasks) {
            taskService.complete(task.getId(), null);
            System.out.println("完成任务： "+task.getName());
        }
        return new ResultEntity(ResultStatus.SUCCESS, "完成任务");
    }
}
